<?php

if (!defined('CORE_PATH'))
    die('Access Denied');

class StatsManager extends Controller {

    // determines if the stats manager should record statistics or not
    private $recordStats, $recordLocalStats;
    // keeps a set of system setting keys to be used by this manager
    private $settingKeys = array(
        "RecordStats" => "RecordStats",
        "RecordLocalStats" => "RecordLocalStats"
    );
    protected $models = array('SiteStatistic');

    function __construct() {
        $system = new SystemManager();
        $this->recordStats = $system->getSetting($this->settingKeys['RecordStats']);
        $this->recordLocalStats = $system->getSetting($this->settingKeys['RecordLocalStats']);
    }

    /**
     * Records a page visit by first checking if a page visit for the current
     * day has been recorded, else it add a new record for the day. If a record
     * exists, it will update the visit count for the day
     *
     * @param String $url
     * @param String $title
     * @param String $referer
     */
    function recordPageVisit($siteid, $title, $url = '', $referer = '') {
        // if we are not to record stats at all then exit
        if ($this->recordStats == 'false') {
            return;
        }

        // if we are recording stats, but we are not to record localhost stats, then exit
        if ($this->recordLocalStats == 'false' && $_SERVER['HTTP_HOST'] == 'localhost') {
            return;
        }

        $date = date('Y-m-d');

        // get a reference to the database object
        $db = $this->getDatabase();

        // if no url is specified, then determine the url from the REQUEST_URI
        if ($url == '') {
            $url = $_SERVER['REQUEST_URI'];
        }

        // if the referer page is not specified, determine it from the HTTP_REFERER
        if ($referer == '' && isset($_SERVER['HTTP_REFERER'])) {
            $referer = $_SERVER['HTTP_REFERER']; // referer page
        }

        // determine if the current url has been recorded for today
        $count = $this->SiteStatistic->count( array(
            'filter' => array('PageURL' => $url, 'ViewDate' => $date)
        ));
        
        // check if a record for the url exists today
        // if a record exists, then update the ViewCount
        if ( $count > 0) {
            
            $this->SiteStatistic->updateAll( array('ViewCount' => 'ViewCount + 1'), array('PageURL' => $url, 'ViewDate' => $date));

            // if record does not exist, insert a new record for the day
        } else {
            $stat = new SiteStatistic( array(
                'SiteID' => $siteid,
                'PageURL' => $url,
                'PageTitle' => $title,
                'RefererURL' => $referer,
                'ViewDate' => date('Y-m-d'),
                'ViewCount' => 1
            ));
            $stat->save();
        }
    }

    /**
     * Returns the total visits for the specified site. The date is not specified,
     * the system will return total visits for the current day
     *
     * @param int $site the ID of the site to obtain data for
     * @param String $date the date for which to obtain the results
     * @return int an integer representing the total visits to the entire site
     */
    public function getTotalVisitsFor($site, $date = '') {
        if ($date == '') {
            $date = date('Y-m-d');
        }

        $stat = $this->SiteStatistic->find( array(
            'fields' => array('sum(ViewCount) as cnt'),
            'filter' => array('SiteID' => $site, 'ViewDate' => $date)
        ));
        
        return $stat->getData('cnt');
    }

    /**
     * Returns the statistics data for the specified site as an array. If the
     * date for which data is required is not specified, data for the current
     * day will be returned.
     *
     * <p>A limit may also be placed on the amount of data that is returned. Hence,
     * if a limit value of 10, only 10 records will be returned from the database
     * ordered in descending order based on the total visits. The default limit
     * value is 20.
     *
     * @param int $site the ID of the site to return data for
     * @param String $date a string representation of the date to return data for
     * @param int $limit the limit on the amount of data to be returned
     * @return array an array containing the statistical data
     */
    public function getSiteStatsData($site, $date = '', $limit = 20) {
        if ($date == '') {
            $date = date('Y-m-d');
        }

        return $this->SiteStatistic->find( array(
            'fields' => array('PageTitle','PageURL','sum(ViewCount) as Total'),
            'filter' => array('SiteID' => $site, 'ViewDate' => $date),
            'group' => array('PageTitle'),
            'order' => array('Total' => 'desc'),
            'limit' => $limit
        ));
    }

    /**
     * Clears all statistics data for the specified date for the specified
     * site
     *
     * @param int $site the database record ID of the site to clear data for
     * @param date $date the date for which stats at to be cleared
     * @return boolean true if the data is cleared successfully or false otherwise
     */
    public function clearSiteStatsData($site, $date = '') {
        if ($date == '') {
            $date = date('Y-m-d');
        }
        
        $this->SiteStatistic->deleteAll(array('SiteID' => $site, 'ViewDate' => $date));
    }

    public function clearAllSiteStatsData($site) {

        $this->SiteStatistic->deleteAll(array('SiteID' => $site));

        return true;
    }

}

?>